<!--选择框组件-->
<template>
  <BasicModal v-bind="$attrs" @register="register" :title="modalTitle" width="800px" @ok="handleOk" destroyOnClose @visible-change="visibleChange">
    <BasicTable @register="registerTable" :rowSelection="rowSelection" :searchInfo="searchInfo"></BasicTable>
  </BasicModal>
</template>
<script lang="ts">
import { defineComponent, ref, unref, watch } from 'vue';
import { BasicTable } from '@/components/table';
import { BasicModal, useModalInner } from '@/components/modal';
import { useSelectModal } from '../../hooks/useSelectModal';
import { useAttrs } from '@pkg/use';
import { useBaseTable } from '@/hooks';
import { selectProps } from './props/props';

export default defineComponent({
  name: 'SelectModal',
  components: { BasicTable, BasicModal },
  props: {
    ...selectProps,
    //选择框标题
    modalTitle: {
      type: String,
      default: '',
    },
    //查询表单配置
    formConfig: {
      type: Object,
    },
    //表格列配置
    columns: {
      type: Object,
      default: [],
    },
  },
  emits: ['register', 'getSelectResult', 'clearSelectOptions'],
  setup(props, { emit }) {
    const attrs = useAttrs();
    //注册弹框
    const [register, { closeModal }] = useModalInner();
    const getBindValue: any = Object.assign({}, unref(props), unref(attrs));
    const [{ rowSelection, indexColumnProps, visibleChange, getSelectResult, getFormConfig }] = useSelectModal(getBindValue);
    //配置table
    const { tableContext } = useBaseTable({
      designScope: 'adv-template',
      tableProps: {
        canResize: false,
        bordered: true,
        size: 'small',
        showTableSetting: false,
        showActionColumn: false,
        rowKey: getBindValue.rowKey,
        //分页列表接口
        listUrl: getBindValue.api,
        columns: getBindValue.columns,
        formConfig: getFormConfig,
        clickToRowSelect: true,
      },
    });
    const [registerTable, { reload }, { hasSelectedRows }] = tableContext;
    //预览框状态
    const previewVisible = ref<boolean>(false);

    const searchInfo: any = ref(props.params);

    /**
     * 监听params变化
     */
    watch(props.params, () => {
      console.info('BasicModal-props.params', props.params);
      //清空选择项
      emit('clearSelectOptions');
    });

    /**
     * 确定选择
     */
    function handleOk() {
      getSelectResult((options, values) => {
        //回传选项和已选择的值
        emit('getSelectResult', options, values);
        //关闭弹窗
        closeModal();
      });
    }

    /**
     * 预览图片
     */
    function handleOpen() {
      previewVisible.value = true;
    }

    return {
      handleOk,
      searchInfo,
      previewVisible,
      registerTable,
      register,
      indexColumnProps,
      handleOpen,
      visibleChange,
      getBindValue,
      getFormConfig,
      rowSelection,
    };
  },
});
</script>
